package com.dupf.product.web.controller.product;

import com.dupf.common.base.BaseController;
import com.dupf.common.util.ItvJsonUtil;
import com.dupf.product.common.constant.ProductResult;
import com.dupf.product.common.constant.ProductResultConstant;
import com.dupf.product.dao.model.ProductCategory;
import com.dupf.product.dao.model.ProductCategoryExample;
import com.dupf.product.dao.smodel.ProductCategorySpe;
import com.dupf.product.rpc.api.ProductCategoryService;
import com.dupf.product.rpc.api.ProductCollectRecordService;
import com.dupf.product.rpc.api.ProductCollectService;
import com.dupf.product.rpc.api.ProductDetailService;
import com.google.common.base.Splitter;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 产品controller
 * Created by dupf on 2018/3/20.
 */
@Controller
@Api(value = "产品管理", description = "产品管理")
@RequestMapping("/product/category")
public class ProductCategoryController extends BaseController {

    private static final Logger LOGGER = LoggerFactory.getLogger(ProductCategoryController.class);

    @Autowired
    private ProductCategoryService productCategoryService;

    @Autowired
    private ProductDetailService productDetailService;

    @Autowired
    private ProductCollectRecordService productCollectRecordService;

    @Autowired
    private ProductCollectService productCollectService;

    @ApiOperation(value = "按分类级别获取")
    @RequestMapping(value = "/{pid}", method = RequestMethod.GET)
    @ResponseBody
    public Object categoryByIds(@PathVariable("pid") int pid) {

        ProductCategoryExample productCategoryExample = new ProductCategoryExample();
//        productCategoryExample.createCriteria().andPidEqualTo(pid);

        List<ProductCategory> list = productCategoryService.selectByExample(productCategoryExample);
        List<ProductCategory> list1 = list.stream().filter(p->p.getPid().equals(0)).sorted(Comparator.comparingInt(ProductCategory::getId)).collect(Collectors.toList());

//        value: 'zhejiang',
//                label: 'Zhejiang',
//                children: [{
        JSONArray resultArray = new JSONArray();
        list1.forEach(p->{
            JSONObject data = new JSONObject();
            data.put("value", p.getId());
            data.put("label", p.getName());
            data.put("children", getChildrenList(list, p.getId()));
//            p.setChildren(getChildrenList(list, p.getId()));
            resultArray.add(data);
        });

        return new ProductResult(ProductResultConstant.SUCCESS, resultArray);
    }

    private JSONArray getChildrenList(List<ProductCategory> list, Integer id) {
        List<ProductCategory> childrenList = list.stream().filter(p->p.getPid().equals(id)).sorted(Comparator.comparingInt(ProductCategory::getId)).collect(Collectors.toList());
        JSONArray resultArray = new JSONArray();
        childrenList.forEach(p->{
            JSONObject data = new JSONObject();
            data.put("value", p.getId());
            data.put("label", p.getName());
            data.put("children", getChildrenList(list, p.getId()));
            resultArray.add(data);
        });
        return resultArray;
    }

    @ApiOperation(value = "按分类级别获取")
    @RequestMapping(value = "/level/{pid}", method = RequestMethod.GET)
    @ResponseBody
    public Object level(@PathVariable("pid") int pid) {

        ProductCategoryExample productCategoryExample = new ProductCategoryExample();
        productCategoryExample.createCriteria().andPidEqualTo(pid);

        List<ProductCategory> list = productCategoryService.selectByExample(productCategoryExample);

        return new ProductResult(ProductResultConstant.SUCCESS, list);
    }

    @ApiOperation(value = "搜索分类")
    @RequestMapping(value = "/search/{name}", method = RequestMethod.GET)
    @ResponseBody
    public Object search(@PathVariable("name") String name) throws InterruptedException {

        ProductCategoryExample productCategoryExample = new ProductCategoryExample();
        productCategoryExample.createCriteria().andSubnumEqualTo(0).andNameLike("%" + name + "%");

        List<ProductCategory> list = productCategoryService.selectByExampleForOffsetPage(productCategoryExample, 0, 20);

        List<ProductCategorySpe> resultList = new ArrayList<>();
        List<Integer> pids = new ArrayList<>();
        for (ProductCategory productCategory : list) {
            if (productCategory.getLevel() != 1) {
                pids.add(productCategory.getPid());
            }

            resultList.add(ItvJsonUtil.readValue(ItvJsonUtil.writeValue(productCategory), ProductCategorySpe.class));
        }

        while (pids != null && pids.size() > 0) {

            productCategoryExample.clear();
            productCategoryExample.createCriteria().andIdIn(pids);

            list = productCategoryService.selectByExample(productCategoryExample);

            pids.clear();
            for (ProductCategory productCategory : list) {

                // 上級id整理
                if (productCategory.getLevel() != 1) {
                    pids.add(productCategory.getPid());
                }

                // 將結果插入到結果集
                Iterator<ProductCategorySpe> it = resultList.iterator();
                List<ProductCategorySpe> newList = new ArrayList<>();
                while (it.hasNext()) {
                    ProductCategorySpe productCategorySpe = it.next();
                    if (productCategorySpe.getPid().equals(productCategory.getId())) {
                        ProductCategorySpe newProductCategorySpe = ItvJsonUtil.readValue(ItvJsonUtil.writeValue(productCategory), ProductCategorySpe.class);
                        newProductCategorySpe.setSubCategory(productCategorySpe);
                        newList.add(newProductCategorySpe);
                        it.remove();
                    }
                }

                resultList.addAll(newList);
            }
        }

        return new ProductResult(ProductResultConstant.SUCCESS, resultList);
    }

    @ApiOperation(value = "按id获取分类")
    @RequestMapping(value = "/{ids}", method = RequestMethod.GET)
    @ResponseBody
    public Object categoryByIds(@PathVariable("ids") String ids) {
        if (StringUtils.isEmpty(ids)) {
            return new ProductResult(ProductResultConstant.SUCCESS, Collections.emptyList());
        }

        ProductCategoryExample productCategoryExample = new ProductCategoryExample();
        productCategoryExample.createCriteria().andIdIn(
                Splitter.on(',').trimResults().omitEmptyStrings()
                        .splitToList(ids).stream().map(Integer::valueOf).collect(Collectors.toList()));
        productCategoryExample.setOrderByClause("id asc");

        List<ProductCategory> list = productCategoryService.selectByExample(productCategoryExample);

        return new ProductResult(ProductResultConstant.SUCCESS, list);
    }

}